/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-30
 * Time: 0:58
 */

//矩阵区域和
public class Demo {
    public int[][] matrixBlockSum(int[][] mat, int k) {

        int m = mat.length;
        int n = mat[0].length;

        //注意该题下标从0开始
        int[][] dp = new int[m+1][n+1];
        int[][] ret = new int[m][n];//返回矩阵

        //预处理一个二维前缀和数组
        for(int i = 1; i <= m; i++)
            for(int j = 1; j <= n; j++)
                dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + mat[i-1][j-1];



        //使用的前缀,注意,下标映射从0开始，x,y应该加一
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++){
                //构建正确下标
                int x1 = Math.max(0,i-k)+1, y1 = Math.max(0,j-k)+1;
                int x2 = Math.min(m-1,i+k)+1, y2 = Math.min(n-1,j+k)+1;

                //填返回的表
                ret[i][j] = dp[x2][y2] - dp[x1-1][y2] - dp[x2][y1-1] + dp[x1-1][y1-1];
            }

        return ret;
    }
}
